package top.lshaci.learning.nio;

import cn.hutool.core.util.StrUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * NioClient
 *
 * @author lshaci
 * @since 1.0.0
 */
public class NioClient {

    public static void main(String[] args) throws IOException {
        final SocketChannel socketChannel = SocketChannel.open();
        // 设置非阻塞模式
        socketChannel.configureBlocking(false);
        final InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

        // 连接服务端
        final boolean connect = socketChannel.connect(inetSocketAddress);

        if (!connect) {
            while (!socketChannel.finishConnect()) {
                System.err.println("连接中...");
            }
        }

        String content = "Hello, NIO! 你好，NIO！";

        final ByteBuffer byteBuffer = StrUtil.byteBuffer(content, "UTF-8");
        // 发送数据
        socketChannel.write(byteBuffer);
        System.err.println("数据发送完成...");
        socketChannel.close();
    }
}
